/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jxtafileshare;

import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.peergroup.PeerGroup;
import net.jxta.platform.NetworkManager;
import net.jxta.protocol.DiscoveryResponseMsg;

import java.util.Enumeration;
import java.util.Scanner;
/**
 *
 * @author Danny
 */
public class DiscoveryClient extends Thread implements DiscoveryListener {

    private transient DiscoveryService discovery;

    /**
     * Constructor for the discovery client
     */
    public DiscoveryClient(DiscoveryService discovery) {
        this.discovery = discovery;
    }

    @Override
    public void run() {
        Scanner keyboard = new Scanner(System.in);
        long waittime = 60 * 1000L;
        String answer;
        int type;
        int count = 5;

        System.out.println("Would you like to search " +
                "for a peer, a peer group, or something else?");
        answer = keyboard.nextLine();
        if(answer.toLowerCase().equals("peer"))
            type = DiscoveryService.PEER;
        else if(answer.toLowerCase().equals("group"))
            type = DiscoveryService.GROUP;
        else
            type = DiscoveryService.ADV;
        try {
            // Add ourselves as a DiscoveryListener for DiscoveryResponse events
            discovery.addDiscoveryListener(this);
            discovery.getRemoteAdvertisements(null, DiscoveryService.ADV,
                    null, null, 1, null);
            while(0 < count--) {
                try {
                    System.out.println("Sleeping for: " + waittime);
                    Thread.sleep(waittime);
                } catch(Exception e) {
                    // ignored
                }
                System.out.println("Sending a Discovery Message");
                // look for any peer
                discovery.getRemoteAdvertisements(null, type,
                        "Name", "Discovery Test", 1, null);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Called when a discovery response is recieved
     */
    public void discoveryEvent(DiscoveryEvent ev) {
        DiscoveryResponseMsg res = ev.getResponse();
        // let's get the responding peer's advertisement
        System.out.println(" [ Got a Discovery Response [" +
                res.getResponseCount() + " elements] from peer: " +
                ev.getSource() + " ]");
        Advertisement adv;
        Enumeration en = res.getAdvertisements();
        if(en != null) {
            while(en.hasMoreElements()) {
                adv = (Advertisement)en.nextElement();
                System.out.println(adv);
            }
        }
    }
}
